package com.cskaoyan.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.io.IOException;
import java.sql.*;

/**
 * @author LiaoLong
 * @date 2021-05-10 9:50
 */

@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringArrayTypeHandler implements TypeHandler<String[]> {
    private ObjectMapper objectMapper = new ObjectMapper();

    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement ps, int index, String[] parameter, JdbcType jdbcType) throws SQLException {
        String params = objectMapper.writeValueAsString(parameter);
        ps.setString(index, params);
    }

    @Override
    public String[] getResult(ResultSet rs, String columnName) throws SQLException {
        String result = rs.getString(columnName);
        return transfer(result);
    }

    @Override
    public String[] getResult(ResultSet rs, int columnIndex) throws SQLException {
        String result = rs.getString(columnIndex);
        return transfer(result);
    }

    @Override
    public String[] getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String result = cs.getString(columnIndex);
        return transfer(result);
    }

    private String[] transfer(String result){
        String[] strings = new String[0];
        if (result != null && !"".equals(result)){
            try {
                strings = objectMapper.readValue(result, String[].class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return strings;
    }
}
